﻿
//***********************************************************************
// * Module:   TbBstFastprocessHandler
// * 作者:  曹荣芝
// * Modified: 2013-05-06
// * Purpose: Definition of the Class TbBstFastprocessHandler 业务逻辑处理Handler类
// ***********************************************************************/

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using XWG.Framework.MSException;
using XWG.Framework.AuthUtility;
using XWG.Framework.AuthEntity;
using XWG.Framework.AuthSPConst;
using XWG.Framework.AuthBLL;
using XWG.JWBST.JWBSTEntity;
using XWG.JWBST.JWBSTSPConst;
using System.Web.Script.Serialization;
using System.Data;
using XWG.Framework.Query;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using XWG.JWBST.JWBSTBLL;
using XWG.Framework;
using System.Collections;
using JWBSTAPP.CommonClass;
using JdSoft.Apple.Apns.Notifications;
namespace JWBSTAPP.AjaxServer
{
    /// <summary>
    /// TbBstFastprocessHandler 的摘要说明
    /// </summary>
    public class TbBstFastprocessHandler : JWBSTAPP.CommonClass.HttpHandlerBase, System.Web.SessionState.IRequiresSessionState
    {

        #region 添加记录
        ///// <summary>
        ///// 添加记录
        ///// </summary>
        //protected void AddRecord()
        //  {
        //       HttpContext context = HttpContext.Current;
        //      context.Response.ContentType = "text/plain";
        //      ResultModel mResultModel = new ResultModel(); //初始化返回类型
        //      try
        //      {

        //      TbBstFastprocess mTbBstFastprocess = new TbBstFastprocess();
        //      mTbBstFastprocess.FastId = Guid.NewGuid().ToString(); //主键
        //           mTbBstFastprocess.FastLsh = context.Request.Form["texFastLsh"]; //事故流水号
        //           mTbBstFastprocess.FastAddress = context.Request.Form["texFastAddress"]; //事故发生区域
        //           mTbBstFastprocess.FastLpna = context.Request.Form["texFastLpna"]; //报案人车牌号
        //           mTbBstFastprocess.FastLpnb = context.Request.Form["texFastLpnb"]; //事故相关车牌号
        //           mTbBstFastprocess.FastPhonea = context.Request.Form["texFastPhonea"]; //报案人手机号
        //           mTbBstFastprocess.FastPhoneb = context.Request.Form["texFastPhoneb"]; //事故相关人手机号
        //           mTbBstFastprocess.FastGpsJd = context.Request.Form["texFastGpsJd"]; //事故发生地经度
        //           mTbBstFastprocess.FastGpsWd = context.Request.Form["texFastGpsWd"]; //事故发生地纬度
        //           mTbBstFastprocess.FastUptime = context.Request.Form["texFastUptime"]; //事故上传时间
        //           mTbBstFastprocess.FastAuditresult = context.Request.Form["texFastAuditresult"]; //事故审核结果
        //           mTbBstFastprocess.FastAudittime = context.Request.Form["texFastAudittime"]; //事故审核时间
        //           mTbBstFastprocess.FastAuditid = context.Request.Form["texFastAuditid"]; //事故审核人ID
        //           mTbBstFastprocess.FastAuditstatus = context.Request.Form["texFastAuditstatus"]; //事故审核状态  0未审核 1已审核
        //           mTbBstFastprocess.FastSound = context.Request.Form["texFastSound"]; //事故声音描述存放路径
        //           mTbBstFastprocess.FastDel = context.Request.Form["texFastDel"]; //删除标记

        //      mResultModel = TbBstFastprocessBLL.Insert(mTbBstFastprocess,context.Session["UserID"], true); //新建操作
        //      context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
        //      }
        //      catch (Exception ex)
        //      {
        //          MSEx.DealErr(ex, "");
        //          mResultModel.ErrorCode = -9999;
        //          mResultModel.ISSucceed = false;
        //          context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
        //      }
        //  }
        #endregion

        #region 删除记录
        /// <summary>
        /// 删除记录
        /// </summary>
        protected void DeleteRecord()
        {

            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                string[] arryParamKey = context.Request.Params["id"].ToString().Split(',');
                if (arryParamKey.Length == 0)
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                TbBstFastprocess mTbBstFastprocess = new TbBstFastprocess();
                foreach (var paramKey in arryParamKey)
                {
                    var Fastprocess = TbBstFastprocessBLL.Load(paramKey);
                    mResultModel = TbBstFastprocessBLL.Delete(paramKey, context.Session["UserID"], true); //删除对应的信息
                    var Fileprocess = TbBstFastprocessFileBLL.GetPicByLSH(Fastprocess.FastLsh);
                    foreach (var item in Fileprocess)
                    {
                        TbBstFastprocessFileBLL.Delete(item.Fileid, context.Session["UserID"], true);
                    }
                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel));//序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion

        #region 审核记录
        /// <summary>
        /// 审核记录
        /// </summary>
        protected void EditRecord()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            TbBstFastprocess mTbBstFastprocess = new TbBstFastprocess();
            int Mark = -1;  //数据源标志 Mark 0 济南民生警务   Mark 1 101车主服务
            string paramKey = context.Request.Params["id"];
            try
            {
                string zr1 = "";
                string zr2 = "";
                string zr3 = "";
                string zr4 = "";
                if (string.IsNullOrEmpty(paramKey))
                {
                    mResultModel.ErrorCode = -9991;
                    mResultModel.ISSucceed = false;
                    context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回    
                    return;
                }
                mTbBstFastprocess = TbBstFastprocessBLL.Load(paramKey); //根据键值获取实体信息
                if (mTbBstFastprocess != null)
                {
                    if (mTbBstFastprocess.FastAuditstatus != "1")
                    {
                        var mUser = AppOrganizatiOnUserBLL.Load(context.Session["UserID"].ToString());
                        ////拼接处理结果
                        if (!string.IsNullOrEmpty(context.Request.Form["selZR1"]))
                        {
                            zr1 = context.Request.Form["selZR1"];
                        }
                        if (zr1 == "1")
                        {
                            zr3 = "全部责任";
                        }
                        else
                            if (zr1 == "0.5")
                            {
                                zr3 = "同等责任";
                            }
                            else
                            {
                                zr3 = "无责任";
                            }
                        if (!string.IsNullOrEmpty(context.Request.Form["selZR2"]))
                        {
                            zr2 = context.Request.Form["selZR2"];
                        }
                        if (zr2 == "1")
                        {
                            zr4 = "全部责任";
                        }
                        else
                            if (zr2 == "0.5")
                            {
                                zr4 = "同等责任";
                            }
                            else
                            {
                                zr4 = "无责任";
                            }
                        string result = "事故责任方:" + context.Request.Form["txtA"] + "责任为:" + zr3 + "。事故责任方:" + context.Request.Form["txtB"] + "责任为:" + zr4 + "。";
                        if (mTbBstFastprocess.FastMark == "0" || string.IsNullOrEmpty(mTbBstFastprocess.FastMark))
                        {
                            //数据为济南民生警务手机端上传
                            Mark = 0;
                        }
                        else
                        {
                            //101车主服务上传
                            Mark = 1;
                        }
                        mTbBstFastprocess.FastAuditresult = result; //事故审核结果
                        mTbBstFastprocess.FastAddress = context.Request.Form["selFastAddress"];////事故发生区域
                        mTbBstFastprocess.FastAudittime = DateTime.Now; //事故审核时间
                        mTbBstFastprocess.FastAuditid = mUser.UserName; //事故审核人ID
                        mTbBstFastprocess.FastAuditstatus = "1"; //事故审核状态  0未审核 1已审核
                        //mTbBstFastprocess.FastSound = context.Request.Form["texFastSound"]; //事故声音描述存放路径
                        // mTbBstFastprocess.FastDel = context.Request.Form["texFastDel"]; //删除标记

                        mResultModel = TbBstFastprocessBLL.Update(mTbBstFastprocess, context.Session["UserID"], true); //新建操作
                        if (mResultModel.ISSucceed)
                        {
                            if (string.IsNullOrEmpty(mTbBstFastprocess.FastToken))
                            {

                            }
                            else
                            {
                                string mes = "您所提交的" + mTbBstFastprocess.FastLsh + "事故已审核";
                                Push(mes, mTbBstFastprocess.FastToken,Mark);
                            }
                        }
                    }
                }
                else
                {
                    mResultModel.ErrorCode = -9990; //没有获取所需的信息，信息可能已被删除
                    mResultModel.ISSucceed = false;

                }
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9999;
                mResultModel.ISSucceed = false;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
        }

        #endregion

        #region 事故出警
        /// <summary>
        /// 事故出警
        /// </summary>
        protected void CallPolice()
        {
            int Mark = -1;
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            var mUser = AppOrganizatiOnUserBLL.Load(context.Session["UserID"].ToString());
            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                var id = context.Request.Params["id"].ToString();
                var mTbBstFast = TbBstFastprocessBLL.Load(id);//根据键值获取管理员
                ///在这里改组织机构
                if (mTbBstFast.FastMark == "0" || string.IsNullOrEmpty(mTbBstFast.FastMark))
                {
                    Mark = 0;
                }
                else
                {
                    Mark = 1;
                }
                mTbBstFast.FastAudittime = DateTime.Now;
                mTbBstFast.FastAuditstatus = "1";
                mTbBstFast.FastAuditresult = "请在不妨碍交通的地点等候，民警将出警处理。";
                mTbBstFast.FastIspolice = "1";
                mTbBstFast.FastAuditid = mUser.UserName;
                mResultModel = TbBstFastprocessBLL.Update(mTbBstFast, context.Session["UserID"], true); //新建操作
                mResultModel.ISSucceed = true;
                string mes = "您所提交的" + mTbBstFast.FastLsh + "事故已审核";
                Push(mes, mTbBstFast.FastToken, Mark);
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion

        #region 获取实体记录
        /// <summary>
        /// 获取实体记录
        /// </summary>
        protected void GetModel()
        {
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            ResultModel mResultModel = new ResultModel(); //初始化返回类型
            string paramKey = context.Request.Params["id"];
            string json = "";
            try
            {
                TbBstFastprocess mTbBstFastprocess = new TbBstFastprocess(); //声明实体
                TbBstDic mBaseDic = new TbBstDic();
                if (!string.IsNullOrEmpty(paramKey))
                {
                    mTbBstFastprocess = TbBstFastprocessBLL.Load(paramKey); //根据键值获取管理员
                    if (mTbBstFastprocess != null)
                    {
                        IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
                        json = JsonConvert.SerializeObject(mTbBstFastprocess, dtConverter);
                        if (!String.IsNullOrEmpty(mTbBstFastprocess.FastAddress))
                        {
                            var list = TbBstPoliceBLL.GetDicByCodeAndParentnode(mTbBstFastprocess.FastAddress, "Address");
                            mBaseDic = list.SingleOrDefault();
                            Hashtable hashtable = new Hashtable();
                            if (mBaseDic != null)
                            {
                                hashtable.Add("VAddress", mBaseDic.Description);
                                json = JsonString.AddAttribute(json, hashtable);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, "");
                mResultModel.ErrorCode = -9990;
                mResultModel.ISSucceed = false;
                json = JsonConvert.SerializeObject(mResultModel);
            }
            context.Response.Write(json);
        }
        #endregion

        #region 获取数据
        /// <summary>
        /// 获取数据记录
        /// </summary>
        protected void QueryRecord()
        {
            TableMessage tm = new TableMessage();
            HearderMessage hm = new HearderMessage();
            List<HearderMessage> list = new List<HearderMessage>();
            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";
            var mUser = AppOrganizatiOnUserBLL.Load(context.Session["UserID"].ToString());
            string pageSize = context.Request.Form["pageSize"];
            string pageIndex = context.Request.Form["pageIndex"];
            string fastZT = context.Request.Form["selType"];
            string fastLSH = context.Request.Form["txtLSH"];
            string fastDQ = context.Request.Form["txtAddress"];
            string begintime = context.Request.Form["texTimeStart"];
            string endtime = context.Request.Form["texTimeEnd"];
            string code = context.Session["UserCode"].ToString();
            if (String.IsNullOrEmpty(pageSize) || String.IsNullOrEmpty(pageIndex) || !AnyString.IsNumeric(pageSize) || !AnyString.IsNumeric(pageIndex))
                return;
            DataTable dtTbBstFastprocess = new DataTable();
            int intPageSize = Convert.ToInt32(pageSize);
            int intPageIndex = Convert.ToInt32(pageIndex);
            QueryByPage Q = new QueryByPage();
            QueryInfo qInfo = new QueryInfo();
            SqlConditionList sqllist = new SqlConditionList();
            //sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastDel, "1"), SqlLogicOper.AND_LOGIC);
            if (!string.IsNullOrEmpty(fastZT))
            {
                if (fastZT == "2")
                {
                    //添加全部
                }
                else
                {
                    sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastAuditstatus, fastZT), SqlLogicOper.AND_LOGIC);
                }
            }
            else
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastAuditstatus, "0"), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(fastLSH))
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastLsh, fastLSH), SqlLogicOper.AND_LOGIC);
            }
            if (!string.IsNullOrEmpty(fastDQ))
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.LIKE, TbBstFastprocessConst.Columns.FastAddress, '%' + fastDQ + '%'), SqlLogicOper.AND_LOGIC);
            }

            if (!string.IsNullOrEmpty(begintime))
            {
                DateTime dtstart = new DateTime();
                if (DateTime.TryParse(begintime, out dtstart))
                {
                    sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_LESS_THAN, TbBstFastprocessConst.Columns.FastUptime, dtstart), SqlLogicOper.AND_LOGIC);//Convert.ToDateTime(dtstart.ToString("yyyy-MM-dd hh:00:01")))
                }
            }
            if (!string.IsNullOrEmpty(endtime))
            {

                DateTime dtend = new DateTime();
                if (DateTime.TryParse(endtime, out dtend))
                {
                    sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.NOT_MORE_THAN, TbBstFastprocessConst.Columns.FastUptime, dtend), SqlLogicOper.AND_LOGIC);//Convert.ToDateTime(dtend.ToString("yyyy-MM-dd hh:59:59")))
                }
            }
            if (code == "370100000000" || mUser.Bz7 == "370100000000")
            {
                //交通警察支队  查看所有信息
            }
            else if (string.IsNullOrEmpty(code))
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastAddress, "00"), SqlLogicOper.AND_LOGIC);   //如果编号为空则不符合查看条件
            }
            else
            {
                sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastAddress, code), SqlLogicOper.AND_LOGIC);
            }
            sqllist.AddLogic(new SqlConditionList.SqlCondition(SqlCompareOper.EQUAL, TbBstFastprocessConst.Columns.FastComplete, "1"), SqlLogicOper.AND_LOGIC);
            dtTbBstFastprocess = Q.GetRecordByPage("*", sqllist.ToSql(), "FAST_UPTIME", intPageSize, intPageIndex, TbBstFastprocessConst.QTableName, TbBstFastprocessConst.FieldKey, "DESC").Tables[0];
            if (dtTbBstFastprocess != null && dtTbBstFastprocess.Rows.Count > 0)
            {
                for (int i = 0; i < dtTbBstFastprocess.Columns.Count; i++)
                {
                    hm = new HearderMessage();
                    hm.name = dtTbBstFastprocess.Columns[i].Caption;
                    list.Add(hm);
                }
                tm.Header = list;
                tm.data = dtTbBstFastprocess;
                tm.totalCount = Convert.ToString((int)Q.RowCount);
            }
            IsoDateTimeConverter dtConverter = new IsoDateTimeConverter { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" };
            string json = JsonConvert.SerializeObject(tm, dtConverter);
            context.Response.Write(json);
        }
        #endregion

        #region 推送
        /// <summary>
        /// 推送
        /// </summary>
        protected void PushRecord()
        {

            HttpContext context = HttpContext.Current;
            context.Response.ContentType = "text/plain";

            ResultModel mResultModel = new ResultModel(); //声明返回类型
            try
            {
                var id = context.Request.Params["id"].ToString();
                var mTbBstFast = TbBstFastprocessBLL.Load(id);//根据键值获取管理员
                ///在这里改组织机构
                mTbBstFast.FastAddress = context.Request.Form["selFastAddress"];
                mResultModel = TbBstFastprocessBLL.Update(mTbBstFast, context.Session["UserID"], true); //新建操作
                mResultModel.ISSucceed = true;
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }
            catch (Exception ex)
            {
                MSEx.DealErr(ex, ""); //写入异常日志
                mResultModel.ErrorCode = -9999; //-9999代码是系统异常通用代码
                mResultModel.ISSucceed = false; //行为执行失败
                context.Response.Write(JsonConvert.SerializeObject(mResultModel)); //序列化后返回
            }

        }
        #endregion

        #region IOS信息推送

        /// <summary>
        /// ios消息推送
        /// </summary>
        /// <param name="message">要推送的信息</param>
        /// <param name="FastToken">对象的Token</param>
        private static void Push(string message, string FastToken, int Mark)
        {
            string p12File = string.Empty;
            string p12FilePassword = string.Empty;
            if (Mark == 0)
            {
                //济南民生警务
                p12File = "aps_development_for_dot_net.p12";
                p12FilePassword = "19910503";
            }
            else if (Mark == 1)
            {
                //101车主服务
                p12File = "aps_development_for_dot_net.p12";
                p12FilePassword = "19910503";
            }
            else
            { 
                //错误信息
            }
            string testDeviceToken = FastToken;

            string p12Filename = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p12File);
            NotificationService service = new NotificationService(true, p12Filename, p12FilePassword, 1);
            service.SendRetries = 5;
            service.ReconnectDelay = 5000;

            Notification alertNotification = new Notification(testDeviceToken);
            alertNotification.Payload.Alert.Body = message;
            alertNotification.Payload.Sound = "default";
            alertNotification.Payload.Badge = 1;

            if (service.QueueNotification(alertNotification))
            {
                //this.texreturn.AppendText("Notification Queued!");
            }

            else
            {
                // this.texreturn.AppendText("Notification Failed to be Queued!");
            }

            service.Close();

            service.Dispose();
        }
        #endregion

    }
}


